/*
 * Copyright (C) 2012 The Aliyunos Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.way.filemanager.ui.policy;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;

import com.way.filemanager.FileManagerAppFrame;
import com.way.filemanager.R;
import com.way.filemanager.activities.GetContextActivity;
import com.way.filemanager.model.FileSystemObject;
import com.way.filemanager.navigation.NavigationListFragmant.Mode;
import com.way.filemanager.navigation.NavigationListFragmant.SelectMode;
import com.way.filemanager.util.MediaHelper;
import com.way.filemanager.util.MimeTypeHelper;

import hwdroid.dialog.AlertDialog;
import hwdroid.dialog.Dialog;
import hwdroid.dialog.DialogInterface;
import hwdroid.dialog.DialogInterface.OnCancelListener;
import hwdroid.dialog.DialogInterface.OnDismissListener;

import java.io.File;

/**
 * A class with the convenience methods for resolve intents related actions
 */
public final class IntentsActionPolicy {

    private static final String TAG = "IntentsActionPolicy"; //$NON-NLS-1$

    /**
     * Extra field for the internal action
     */
    public static final String EXTRA_INTERNAL_ACTION = "com.aliyunos.filemanager.extra.INTERNAL_ACTION"; //$NON-NLS-1$

    /**
     * Category for all the internal app viewers
     */
    public static final String CATEGORY_INTERNAL_VIEWER = "com.aliyunos.filemanager.category.INTERNAL_VIEWER"; //$NON-NLS-1$

    /**
     * Category for all the app editor
     */
    public static final String CATEGORY_EDITOR = "com.aliyunos.filemanager.category.EDITOR"; //$NON-NLS-1$

    /**
     * Method that opens a {@link FileSystemObject} with the default registered
     * application by the system, or ask the user for select a registered
     * application.
     *
     * @param ctx
     *            The current context
     * @param fso
     *            The file system object
     * @param choose
     *            If allow the user to select the application to open with
     * @param onCancelListener
     *            The cancel listener
     * @param onDismissListener
     *            The dismiss listener
     */
    public static void openFileSystemObject(final Context ctx,
            final FileSystemObject fso, final boolean choose,
            OnCancelListener onCancelListener,
            OnDismissListener onDismissListener) {
        try {
            // Create the intent to open the file
            Intent intent = new Intent();
            intent.setAction(android.content.Intent.ACTION_VIEW);

            // Obtain the mime/type and passed it to intent
            String mime = MimeTypeHelper.getMimeType(ctx, fso);
            Log.v(TAG, "mime:" + mime);
            if((mime != null)&&(mime.equalsIgnoreCase("application/zip"))&&(ctx instanceof FileManagerAppFrame))
            {

                Log.v(TAG, "UnZipDialog:");
                //UnZipDialog dialog = new UnZipDialog(ctx,fso.getFullPath());
                //dialog.show();
                final String[] FileFullPath1 = {fso.getFullPath()};

                ((FileManagerAppFrame)ctx).listLocalPathPaste(null,
                        Mode.paste,SelectMode.Unzip,FileFullPath1);
                return;
            }
            File file = new File(fso.getFullPath());
            if(!file.exists())
            {

                new Handler(ctx.getMainLooper()).post(new Runnable()
                {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        Log.v("rwei", "openFileSystemObject:111");
                        AlertDialog a = new AlertDialog.Builder(ctx)
                        .setTitle(R.string.ali_openfile_error11)
                        .setNegativeButton(R.string.ali_iknow, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                /* User clicked cancel so do some stuff */
                            }
                        }).create();

                        a.show();
                //DialogUtils.fromBottomToTop(a);
                    }

                });

                return;
            }
            if (mime != null) {
                intent.setDataAndType(getUriFromFile(ctx, file), mime);
            } else {
                //intent.setData(getUriFromFile(ctx, file));
                showSelectMimeTypeDialog(ctx,getUriFromFile(ctx, file));
                return ;
            }

            ctx.startActivity(intent);
        } catch (Exception e) {
            //ExceptionUtil.translateException(ctx, e);
            new Handler(ctx.getMainLooper()).post(new Runnable()
            {
                @Override
                public void run() {
                    // TODO Auto-generated method stub

                    AlertDialog a = new AlertDialog.Builder(ctx)
                    .setTitle(R.string.ali_openfile_error)
                    .setNegativeButton(R.string.ali_iknow, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            /* User clicked cancel so do some stuff */
                        }
                    }).create();
                    a.show();

                }

            });
        }
    }

    /**
     * Method that returns the best Uri for the file (content uri, file uri,
     * ...)
     *
     * @param ctx
     *            The current context
     * @param file
     *            The file to resolve
     */
    private static Uri getUriFromFile(Context ctx, File file) {
        ContentResolver cr = ctx.getContentResolver();
        Uri uri = MediaHelper.fileToContentUri(cr, file);
        if (uri == null) {
            uri = Uri.fromFile(file);
        }
        return uri;
    }
    private static void showSelectMimeTypeDialog(Context mActivity,final Uri data)
    {
        final Context mContext = mActivity;
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setItems(R.array.mime_type_item, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                String mime = null;
                String[] items = mContext.getResources().getStringArray(
                        R.array.mime_type_item);
                if (items[which].equalsIgnoreCase(mContext.getResources().getString(
                        R.string.ali_open_mimetype_text))) {
                    mime = "text/*";
                }
                else if (items[which].equalsIgnoreCase(mContext.getResources().getString(
                        R.string.ali_open_mimetype_audio))) {
                    mime = "audio/*";
                }
                else if (items[which].equalsIgnoreCase(mContext.getResources().getString(
                        R.string.ali_open_mimetype_video))) {
                    mime = "video/*";
                }
                else if (items[which].equalsIgnoreCase(mContext.getResources().getString(
                        R.string.ali_open_mimetype_image))) {
                    mime = "image/*";
                }
                try{
                Intent intent = new Intent();
                intent.setAction(android.content.Intent.ACTION_VIEW);
                intent.setDataAndType(data, mime);
                mContext.startActivity(intent);
                }
                catch (Exception e) {
                    //ExceptionUtil.translateException(ctx, e);
                    new Handler(mContext.getMainLooper()).post(new Runnable()
                    {
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub

                            AlertDialog a = new AlertDialog.Builder(mContext)
                            .setTitle(R.string.ali_openfile_error)
                            .setNegativeButton(R.string.ali_iknow, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int whichButton) {
                                    /* User clicked cancel so do some stuff */
                                }
                            }).create();
                            a.show();

                        }

                    });
                }
            }
            });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            }
        });

        Dialog dd = builder.create();
        dd.show();
    }
}
